import React, { useState, useRef, useEffect } from "react";
import "./index.css";
import { getDuoWeiTData,updateTRecord } from "../../utils/auth_access_util";

const CustomDropdown = ({ onSelect, longitude,latitude, placeholder = "Select..." }) => {
  const [duoweiTable, setDuoWeiTable] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [selectedOption, setSelectedOption] = useState(null);
  const dropdownRef = useRef(null);

  // 点击外部关闭菜单
  useEffect(() => {
    async function fetchData() {
      const result = await getDuoWeiTData();
      console.log("result",result);
      setDuoWeiTable(result);
    }
    fetchData();

    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const handleSelect = (option) => {
    setSelectedOption(option);
    onSelect(option);
    setIsOpen(false);
    // updateTRecord(option.record_id,longitude,latitude);
  };

  return (
    <div className="custom-dropdown" ref={dropdownRef}>
      <div className="dropdown-toggle" onClick={() => setIsOpen(!isOpen)}>
        {selectedOption ? selectedOption.fields.工单编号 : placeholder}
        <span className={`arrow ${isOpen ? "up" : "down"}`}></span>
      </div>

      {isOpen && (
        <ul className="dropdown-menu">
          {duoweiTable.map((option) => (
            <li
              key={option.record_id}
              onClick={() => handleSelect(option)}
            >
              {option.fields.工单编号}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default CustomDropdown;
